/*发送消息*/
function send(headUrl, str, time) {
    var html = "<div class='send'><div class=\"time\">"
        + time + "</div><div class='msg'><img src=" + headUrl + " />" +
        "<p style='background-color: #7dab50'><i class='msg_input'></i>" + str + "</p></div></div>";
    upView(html);
}

/*接受消息*/
function show(headUrl, str, time) {
    var html = "<div class='show'><div class=\"time\">" + time + "</div><div class='msg'><img src=" + headUrl + " />" +
        "<p><i class='msg_input'></i>" + str + "</p></div></div>";
    upView(html);
}

/*更新视图*/
function upView(html) {
    $('.message').append(html);
    $('body').animate({scrollTop: $('.message').outerHeight() - window.innerHeight}, 200)
}

//格式化时间
function CurentTime(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm;
    return clock;
}

//格式化时间
function CurentTimeWithSeconds(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var ss = date.getSeconds();
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += "0";
    clock += ss;
    return clock;
}

//跳转到底部
function end() {
    var c = window.document.body.scrollHeight;
    window.scroll(0, c);
}

$(function () {
    // 发送键是否可用
    $('.footer').on('keyup', 'input', function () {
        if ($(this).val().length > 0) {
            $(this).next().css('background', '#114F8E').prop('disabled', true);

        } else {
            $(this).next().css('background', '#ddd').prop('disabled', false);
        }
    })
    //当前用户,即为发送者
    var senderId = JSON.parse(sessionStorage.getItem("user")).id;
    //接收者id
    var receiverId = getParams().receiverId;
    // 接收者
    var receiver;
    // 获取接收者数据
    $.get(baseUrl + "/users/" + receiverId, function (data) {
        receiver = data.data;
        $("#sendImg").attr("src", receiver.headImgUrl);
        $(".receiverName").html(receiver.nickName);
        $(".receiverData").click(function () {
            window.location.href = "/userProfiles.html?id=" + receiverId;
        });
    });

    // 发送请求,通过发送者id和接受者id获取到两者之间的信息
    $.get(baseUrl + "/chatRecords/" + senderId + "/" + receiverId + "/messages", function (data) {
        $.each(data, function (index, ele) {
            // 通过结果中发送者的id判断哪个是当前用户,是当前用户,就显示在右边
            if (ele.sender.id == senderId) {
                $(".message").append('<div class="show">\n' +
                    '      <div class="time">' + CurentTime(new Date(ele.creatime)) + '</div>\n' +
                    '      <div class="msg">\n' +
                    '        <img src="' + ele.sender.headImgUrl + '" width="40px" alt="" />\n' +
                    '        <p style="background: rgb(74, 198, 0)"></i>' + ele.content + '</p>\n' +
                    '      </div>\n' +
                    '    </div>');
            } else {
                $(".message").append('<div class="send">\n' +
                    '      <div class="time">' + CurentTime(new Date(ele.creatime)) + '</div>\n' +
                    '      <div class="msg">\n' +
                    '        <img src="' + ele.sender.headImgUrl + '" width="40px" alt="" />\n' +
                    '        <p><i class="msg_input"></i>' + ele.content + '</p>\n' +
                    '      </div>\n' +
                    '    </div>');
            }
        });
        end();
    });

    var websocket;
    /* 判断浏览器是否支持 */
    if ('WebSocket' in window) {
        console.log("此浏览器支持websocket");
        websocket = new WebSocket("ws://127.0.0.1:8888/websocketDemo/" + user.id);
    } else if ('MozWebSocket' in window) {
        alert("此浏览器只支持MozWebSocket");
    } else {
        alert("此浏览器只支持SockJS");
    }
    /* 定义onopen方法,第一次连接调用 */
    websocket.onopen = function (evnt) {
        $("#tou").html("链接服务器成功!")
    };
    /* 定义信息处理方法，接收信息时调用 */
    websocket.onmessage = function (evnt) {
        $(".message").append('<div class="send">\n' +
            '      <div class="time">' + CurentTime(new Date()) + '</div>\n' +
            '      <div class="msg">\n' +
            '        <img src="' + receiver.headImgUrl + '" width="40px" alt="" />\n' +
            '        <p><i class="msg_input"></i>' + evnt.data + '</p>\n' +
            '      </div>\n' +
            '    </div>');
    };
    websocket.onerror = function (evnt) {
    };
    /* 定义onclose方法，断开连接时调用 */
    websocket.onclose = function (evnt) {
        $("#tou").html("与服务器断开了链接!")
    }
    $('#sendBtn').bind('click', function () {
        send();
        end();
    });

    /* 发送消息 */
    function send() {
        var message = $("[name='message']").val();
        if (message == "") {
            //如果没有信息,直接返回
            $(document).dialog({
                type: 'notice',
                content: '<span class="info-text">内容不能为空</span>',
                autoClose: 1000,
                position: 'bottom'
            });
            return;
        };

        if (websocket != null) {
            var message = document.getElementById('message').value;

            // 发送者的消息显示
            $(".message").append('<div class="show">\n' +
                '      <div class="time">' + CurentTime(new Date()) + '</div>\n' +
                '      <div class="msg" >\n' +
                '        <img src="' + user.headImgUrl + '" width="40px" alt="" />\n' +
                '        <p style="background: rgb(74, 198, 0)"></i>' + message + '</p>\n' +
                '      </div>\n' +
                '    </div>');
            // 将消息发送到后台
            $.get(baseUrl + "/message/senderId/" + user.id + "/receiverId/" + getParams().receiverId + "?content=" + message, function (data) {
                console.log(data);
            });
            websocket.send(message);
        } else {
            alert('未与服务器链接.');
        };
        // 发送完后清空信息框内容
        $("[name='message']").val("");
        $("[name='message']").next().css('background', '#ddd').prop('disabled', false);
    }
});